import React, { useEffect, useRef } from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, UnlockOutlined } from '@ant-design/icons';
import request from '@/utils/request'
import './index.scss'
export default function Login(props) {
    const myRef = useRef();
    //登录
    const onFinish = async (values) => {
        const { data } = await request.post('/user/login', { ...values });
        if (data.msg === '用户不存在') {
            message.error('用户不存在')
            return;
        }
        if (data.msg === '密码错误') {
            message.error('密码错误')
            return;
        }
        if (data.success) {
            localStorage.setItem('token', JSON.stringify(data.data.token))
            props.history.push('/subject')
        }
    };
    //注册
    const goToReg = () => {
        props.history.push('/reg')
    }
    useEffect(() => {
        //获取注册成功的表单信息并设置为登录表单的内容
        myRef.current.setFieldsValue(props.location.state);
    }, [])
    return (
        <div className="form_box">
            <Form
                name="basic"
                onFinish={onFinish}
                initialValues={{ account: '', password: '' }}
                autoComplete="off"
                ref={myRef}
            >
                <h3 className="login_title">系统登录</h3>
                <Form.Item
                    name="account"
                    rules={[{ required: true, message: '输入用户' }]}
                    className="inp"
                >
                    <Input
                        prefix={<UserOutlined style={{ fontSize: 20 }} />}
                        style={{
                            height: 50,
                            background: 'rgba(0, 0, 0, .1)',
                        }}
                        placeholder="学号/职工号"
                        autoComplete="on"
                    />
                </Form.Item>

                <Form.Item
                    name="password"
                    rules={[{ required: true, message: '请输入密码' }]}
                    className="inp"
                >
                    <Input.Password
                        prefix={<UnlockOutlined style={{ fontSize: 20 }} />}
                        placeholder="密码"
                        style={{
                            height: 50,
                            background: 'rgba(0, 0, 0, .1)',
                        }}
                    />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        登录
                    </Button>
                </Form.Item>
                <div className="goToReg" onClick={goToReg}>
                    学生注册
                </div>
            </Form>
        </div>
    )
}
